package com.cdtu.sys.service.impl;

import com.cdtu.sys.domain.LogInfo;
import com.cdtu.sys.domain.Role;
import com.cdtu.sys.domain.User;
import com.cdtu.sys.mapper.LogInfoMapper;
import com.cdtu.sys.mapper.RoleMapper;
import com.cdtu.sys.service.ILogInfoService;
import com.cdtu.sys.utils.DataGridView;
import com.cdtu.sys.utils.getIpUtils;
import com.cdtu.sys.domain.LogInfoVo;
import com.cdtu.sys.domain.RoleVo;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import java.util.Date;
import java.util.List;

@Service
@Slf4j
public class LogInfoServiceImpl implements ILogInfoService {

    @Autowired
    private LogInfoMapper logInfoMapper;
    @Autowired
    private RoleMapper roleMapper;
    /**
     * 分页查询日志
     * @param logInfoVo
     * @return
     */
    @Override
    public DataGridView queryAllLogInfo(LogInfoVo logInfoVo) {
        Page<LogInfo> page = PageHelper.startPage(logInfoVo.getPage(),logInfoVo.getLimit());
        List<LogInfo> data =  logInfoMapper.queryAllLogInfo(logInfoVo);
        return new DataGridView(page.getTotal(),data);
    }

    @Override
    public void deleteLogInfo(Integer id) {
        logInfoMapper.deleteByPrimaryKey(id);
    }

    @Override
    public void deleteBatchLogInfo(LogInfoVo logInfoVo) {
        for (Integer id : logInfoVo.getIds()) {
            deleteLogInfo(id);
        }
    }

    /**
     * 添加登录日志信息
     * @param user
     * @param request
     */
    @Override
    public void addLogInfo(User user, HttpServletRequest request) {
        log.info("用户信息：{}",user.toString());
        log.info("ip地址：{}", getIpUtils.getIpAddr(request));

        List<Role> roles = roleMapper.queryAllRole(new RoleVo());

        LogInfo logInfo = new LogInfo();
//        logInfo.setLoginname(user.getLoginname());
        logInfo.setLoginname(roles.get(user.getType()-1).getRolename()+"-"+user.getLoginname());
        logInfo.setLoginip(getIpUtils.getIpAddr(request));
        logInfo.setLogintime(new Date());
        logInfoMapper.addLogInfo(logInfo);

    }
}
